<?php

namespace app\admin\controller;

use think\Db;

class Article extends Authorized
{

    public function index()
    {
        $category_list = Db::table('category')->where('type',1)->order('id')->select();
        $this->assign('category_list', $category_list);
        return $this->fetch();
    }


    public function getList()
    {
        $get_data=$this->request->get();
        $post_data = $this->request->post();

        $page = $get_data['page'];
        $limit = $get_data['limit'];

        $keywords = input('keywords');
        $cid = input('cid');
        $where=[];


        if (!empty($keywords)){
            $where['a.title']=['like','%'.$keywords.'%'];
        }
        if (!empty($cid)){
            $where['a.cid']=$cid;
        }

        $count=Db::table('article a')->where($where)->count();
        $rows=Db::table('article a')->field('a.*,c.title category_name')->join('category c','a.cid=c.id','left')
            ->where($where)
            ->order('a.sort desc,a.created_at desc')
            ->page($page, $limit)
            ->select();
        return json(['code' =>0,'count' =>$count,'msg' =>'','data'=>$rows]);
    }

    public function add()
    {
        $post_data = $this->request->post();
        if($post_data){
            $post_data['created_at'] = $post_data['updated_at'] = time();
            Db::table('article')->startTrans();
            $id =Db::table('article')->insertGetId($post_data);
            if (false === $id) {
                Db::table('article')->rollback();
                return json(['code' =>1,'count' =>0,'msg' =>'添加失败','data'=>'']);
            } else {
               Db::table('article')->commit();
                return json(['code' =>0,'count' =>0,'msg' =>'添加成功','data'=>'']);
            }
        }
       return $this->fetch();
    }

    public function edit()
    {
        $post_data = $this->request->post();
        if($post_data){
            $post_data['updated_at'] = time();
            $result =Db::table('article')->where('id', $post_data['id'])->setField($post_data);
            if (false === $result) {
                return json(['msg' =>'失败', 'code' =>1]);
            } else {
                return json(['msg' =>'成功', 'code' =>0]);
            }
        }


        $article=Db::table('article')->field('article.*,category.title category_name')
            ->join('category','category.id= article.cid')
            ->where('article.id' , input('id'))
            ->find();
        $this->assign('article', $article);

       return $this->fetch();
    }


    public function del()
    {
        $post_data = $this->request->post();
        if($post_data){
            $result =Db::table('article')->where('id', $post_data['id'])->delete();
            if (false === $result) {
                return json(['msg' =>'删除失败', 'code' =>1]);
            } else {
                return json(['msg' =>'删除成功', 'code' =>0]);
            }
        }
    }
}